package com.weme.common.util;

import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.style.ReplacementSpan;

public class LinearGradientFontSpan extends ReplacementSpan {
    private int mSize;
    private int startColor;
    private int endColor;


    public LinearGradientFontSpan(int startColor, int endColor) {
        this.startColor = startColor;
        this.endColor = endColor;

    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        mSize = (int) (paint.measureText(text, start, end));
        Paint.FontMetricsInt metrics = paint.getFontMetricsInt();
        if (fm != null) {
            fm.top = metrics.top;
            fm.ascent = metrics.ascent;
            fm.descent = metrics.descent;
            fm.bottom = metrics.bottom;
        }

        return mSize;
    }
    private Rect mRec;
    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
//        paint.getTextBounds(text,0,text.length(),mRec);

        LinearGradient lg = new LinearGradient(0, 0,  paint.measureText(text.toString()), paint.descent() - paint.ascent(),
                startColor,
                endColor,
                Shader.TileMode.REPEAT); //从上到下渐变
        paint.setShader(lg);

        canvas.drawText(text, start, end, x, y, paint);//绘制文字
    }

}